package ice.hufs.ac.kr.push;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.xml.datatype.*;

import android.app.*;
import android.content.*;
import android.hardware.*;
import android.hardware.Camera.*;
import android.net.*;
import android.nfc.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.SurfaceHolder.*;
import android.view.View.OnClickListener;
import android.widget.*;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {
	private static Object forced = null;
	AsyncTask<?, ?, ?> regIDInsertTask;
	TextView message;
	TextView txt_Message;
	ProgressDialog loagindDialog;
	String regId ;
	String myResult ;
	//	String str_key = GCMIntentService.re_message;

	Button btn_Save;
	private String path;

	Button callBtn;

	Handler dnHandler;

	Intent ac_intent;
	Intent dn_intent;


	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;

	private TextView tagDesc;

	String storeTag ;
	String number1;
	String number2;

	//	public static String[] valueTest;
	//GCMIntentService gis;

	String TAG = MainActivity.class.getName();

	int valueT = 0;
	int valueF = 0;

	//private CameraView cView;

	NetworkData nd ;

	private final String SERVER_ADDRESS = "http://dislab.iptime.org:2324/requestinfo/confirm_request.php";

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//		Log.e("re_message", str_key);
		message=(TextView)findViewById(R.id.re_message);
		//press = (Button)findViewById(R.id.btn);


		//		if(GCMIntentService.re_message!=null){
		//			message.setText(GCMIntentService.re_message);
		//			//	valueTest[GCMIntentService.count] = GCMIntentService.re_message;
		//		} else{
		registerGcm();

		//		cView = new CameraView(this);
		//		FrameLayout f1 = (FrameLayout)findViewById(R.id.cView);
		//		f1.addView(cView);
		//		}

		//		valueTest = new String[100];
		//		initValueTest();


		//gis = new GCMIntentService();

		//		press.setOnClickListener(new OnClickListener() {
		//
		//			public void onClick(View arg0) {
		//				// TODO Auto-generated method stub
		//				Log.e("GCMIntentService.re_message", GCMIntentService.re_message);
		//				message.setText(GCMIntentService.re_message);
		//			}
		//		});

		//		btn_Save.setOnClickListener(new OnClickListener() {
		//			
		//			public void onClick(View v) {
		//				// TODO Auto-generated method stub
		//				WriteLog();
		//			}
		//		});

		tagDesc = (TextView)findViewById(R.id.tagDesc);

		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		Intent intent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		//		str_key = this.getIntent().getStringExtra("msg");
		//
		//		txt_Message.setText(str_key);

		callBtn = (Button)findViewById(R.id.callBtn);

		callBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:/") );
				startActivity(callIntent);
			}
		});

	}



	@Override
	protected void onPause() {
		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(this);
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (nfcAdapter != null) {
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		long time = System.currentTimeMillis ();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

		Date dd = new Date(time);
		String strTime = sdf.format(dd);
		String[] curTime;
		String[] curYMD;
		String curDay = null;
		String no1 = null;
		String no2 = null;
		super.onNewIntent(intent);
		String mTAG = " onNetIntent";

		curTime = strTime.split(" ");
		curYMD = curTime[0].split("/");


//		if(!curDay.equals(curYMD[2])) {
//			curDay = curYMD[2];
//			for(int i = 0; i < GCMIntentService.msgAL.size(); i++ ) {
//				no = GCMIntentService.msgAL.get(i);
//				no = null;
//
//
//			}
//		}	

		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if (tag != null) {
			byte[] tagId = tag.getId();


			//Toast.makeText(this, strTime, Toast.LENGTH_SHORT).show();
			//Toast.makeText(this, curTime[0], Toast.LENGTH_SHORT).show();
			//Toast.makeText(this, curTime[1], Toast.LENGTH_SHORT).show();

			nd = new NetworkData();


			number1 = Integer.toString(tagId[0]);
			number2 = Integer.toString(tagId[1]);
			//			tagDesc.setText("TagID: " + toHexString(tagId));
			//tagDesc.setText("TagID: " + tagId[0] + "   " + tagId[1] +"   "+ tagId[2] +"   "+ tagId[3]);
			//Toast.makeText(this, "태그찍힘", Toast.LENGTH_SHORT).show();
			storeTag = number1+" "+number2;
			tagDesc.setText(storeTag);

			nd.setVisitDate(curTime[0]);
			nd.setVisitTime(curTime[1]);
			nd.setKeyValue(storeTag);
			
			//valueT = 0;
			no1 = "-76 -51";
			no2 = "57 16";


		}

		//valueT = 0;
		//		GCMIntentService.valueCode[GCMIntentService.count] = GCMIntentService.re_message;

		//		Log.e("gis", GCMIntentService.valueCode[GCMIntentService.count]);
		Log.e("storeTag", storeTag);


		Log.e(TAG + " onNewIntent", "GCMIntentService's count = " + GCMIntentService.msgAL.size());


		//		Log.e(TAG + " onNewIntent", "GCMIntentService's count = " + GCMIntentService.re_message);

		for(int i = 0; i < GCMIntentService.msgAL.size(); i++ ) {
			//if(storeTag.equals(no1) || storeTag.equals(no2)) {
			if(storeTag.equals(GCMIntentService.msgAL.get(i))) {
				//				Log.e("GCM 코드1", i + " : " + GCMIntentService.msgAL.get(i));
				//				Log.e("태깅한 코드1", storeTag);
				//				if(storeTag.equals(GCMIntentService.msgAL.get(i))) {


				//					ac_intent = new Intent(MainActivity.this, AcceptedActivity.class);
				//
				//					startActivity(ac_intent);
				valueT++;
				//break;
				//				}
				//				continue;

			}
			else {
				//				Log.e("GCM 코드1", i + " : " + valueTest[i]);
				//				Log.e("태깅한 코드1", storeTag);
				//				dn_intent = new Intent(MainActivity.this, DeniedActivity.class);
				//
				//				startActivity(dn_intent);
				valueF++;

			}

			Log.e(TAG + mTAG, "msgALSize = " + GCMIntentService.msgAL.size());
			Log.e(TAG + mTAG, "msgALSize = " + GCMIntentService.msgAL.get(i));


		}

		if(valueT == 1) {
			ac_intent = new Intent(MainActivity.this, AcceptedActivity.class);

			startActivity(ac_intent);
			
			valueT = 0;
			valueF = 0;
		}
		else if(valueF == GCMIntentService.msgAL.size()) {
			dn_intent = new Intent(MainActivity.this, DeniedActivity.class);

			startActivity(dn_intent);
			
			valueT = 0;
			valueF = 0;

		}
		
		valueT = 0;
		valueF = 0;
	}

	public static final String CHARS = "0123456789ABCDEF";

	public static String toHexString(byte[] data) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < data.length; ++i) {
			sb.append(CHARS.charAt((data[i] >> 4) & 0x0F))
			.append(CHARS.charAt(data[i] & 0x0F));
		}
		return sb.toString();
	}

	//	protected void WriteLog() {
	//		// TODO Auto-generated method stub
	//		path = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"save.txt";
	//
	//		File templog = new File(path);
	//
	//
	//		try {
	//			if(!templog.exists())
	//				templog.createNewFile();
	//
	//			RandomAccessFile raf = new RandomAccessFile(path, "rw");
	//			raf.seek(raf.length());
	//			raf.writeBytes(GCMIntentService.re_message);
	//			raf.close();
	//		} catch (Exception e) {
	//			e.printStackTrace();
	//		}
	//	}

	public void registerGcm() {
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		regId = GCMRegistrar.getRegistrationId(this);

		if (regId.equals("")) {
			GCMRegistrar.register(this, "112188264731");
		} else {
			Log.e("reg_id", regId);
		}
		sendAPIkey();
	}

	private void sendAPIkey() {
		String  myNum="���ȣ����";
		regIDInsertTask = new regIDInsertTask().execute(regId, myNum);
	}


	private class regIDInsertTask extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			loagindDialog = ProgressDialog.show(MainActivity.this, "Ű ��� ���Դϴ�..",
					"Please wait..", true, false);
		}

		@Override
		protected Void doInBackground(String... params) {
			HttpPostData(params[0] , params[1]);
			return null;
		}

		protected void onPostExecute(Void result) {
			loagindDialog.dismiss();
		}
	}

	public void HttpPostData(String reg_id , String pnum) { 
		try { 
			URL url = new URL("http://220.67.124.69/pushbackup/gcm_reg_insert.php");       // URL ���� 
			HttpURLConnection http = (HttpURLConnection) url.openConnection();   // ���� 
			//-------------------------- 
			//   ��� ��� ���� - �⺻���� �����̴� 
			//-------------------------- 
			http.setDefaultUseCaches(false);                                            
			http.setDoInput(true);                        
			http.setDoOutput(true);                     
			http.setRequestMethod("POST");         

			http.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
			StringBuffer buffer = new StringBuffer(); 
			buffer.append("reg_id").append("=").append(reg_id).append("&");                 // php ������ �� ���� 
			buffer.append("pnum").append("=").append(pnum);

			OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "EUC-KR"); 
			PrintWriter writer = new PrintWriter(outStream); 
			writer.write(buffer.toString()); 
			writer.flush(); 
			InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR");  
			BufferedReader reader = new BufferedReader(tmp); 
			StringBuilder builder = new StringBuilder(); 
			String str; 
			while ((str = reader.readLine()) != null) {    
				builder.append(str + "\n");                 
			} 

			myResult = builder.toString();   
			//			Log.e("str", str);

		} catch (MalformedURLException e) { 
			// 
		} catch (IOException e) { 
			//  
		} // try 
	} // HttpPostData 

	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		if (keyCode == KeyEvent.KEYCODE_MENU) {  
			if (event.isLongPress()) {  
				return true;  
			}  
		}  
		return super.onKeyDown(keyCode, event);  
	}

	public boolean onKeyLongPress(int keyCode, KeyEvent event) {  
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {  
			return true;  
		}  
		return super.onKeyLongPress(keyCode, event);  
	}

	public void onBackPressed() {

	}

}


//class CameraView extends SurfaceView implements Callback,
//Camera.PictureCallback{
//
//	private SurfaceHolder holder;
//	private Camera camera;
//
//
//	public CameraView(Context context) {
//		super(context);
//
//		holder = this.getHolder();
//		holder.addCallback(this);
//		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//
//	}
//
//	public CameraView(Context context, AttributeSet attrs) {
//		super(context, attrs);
//
//		holder = this.getHolder();
//		holder.addCallback(this);
//		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//
//	}
//
//	public void surfaceCreated(SurfaceHolder holder) {
//		camera = Camera.open();
//		try {
//			camera.setPreviewDisplay(holder);
//		} catch (IOException e) {
//			camera.release();
//			camera = null;
//			e.printStackTrace();
//		}
//
//	}
//
//	public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height) {
//		Camera.Parameters params = camera.getParameters();
//		List<Size> previewSizes = params.getSupportedPreviewSizes();
//		
//		Camera.Size previewSize = previewSizes.get(0);
//		
//		params.setPreviewSize(previewSize.width, previewSize.height);
//		camera.setParameters(params);
//		camera.startPreview();
//	}
//
//	public void surfaceDestroyed(SurfaceHolder holder) {
//		if( null != camera){
//			camera.setPreviewCallback(null);
//			camera.stopPreview();
//			camera.release();
//			camera = null;
//		}
//	}
//
//	public void onPictureTaken(byte[] data, Camera camera) {
//		Toast.makeText(getContext(), "onPictureTaken", Toast.LENGTH_SHORT).show();
//
//		long time = System.currentTimeMillis ();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
//
//		Date dd = new Date(time);
//		String strTime = sdf.format(dd);
//		
//		String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
//		File cfile = new File(sd + "caca");
//		cfile.mkdirs();
//		
//		String path = sd + "caca" + strTime + ".jpg";
//		File file = new File(path);
//		
//		
//		
//		camera.startPreview();
//	}
//
//	public void capture(){
//		camera.takePicture(null, null,this);
//	}
//
//}